package com.example.test_anno_and_aspect.aspect;

import cn.hutool.core.util.ReflectUtil;
import com.example.test_anno_and_aspect.anno.AnnoDemo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;

/**
 * @version 1.0.0
 * Created by cyd on 2022-05-31 10:57:59
 * @ClassName : com.example.test_anno_and_aspect.aspect.AspectDemo
 * @Description : 类描述
 */
@Aspect
@Component
public class AspectDemo {

    @Before(value = " @annotation(com.example.test_anno_and_aspect.anno.AnnoDemo) ")
    public void excetionMethod(JoinPoint joinPoint) {
        // 拿到注解相关信息
        AnnoDemo annoDemo = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(AnnoDemo.class);
        String requestType = annoDemo.requestType().toString();
        // 根据注解信息进行操作
        if ("GET".equals(requestType)) {
            // 获取get请求参数值
            System.out.println("AspectDemo: request typ is get ");
            Object[] args = joinPoint.getArgs();
            // 获取get请求参数名
            String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
            HashMap<String, Object> hashMap = new HashMap<>();
            for (int i = 0; i < parameterNames.length; i++) {
                hashMap.put(parameterNames[i], args[i]);
            }
            hashMap.forEach((key, value) -> System.out.println(key + " --- " + value));
        }

        if ("POST".equals(requestType)) {
            // 获取post请求参数
            System.out.println("AspectDemo: request typ is post ");
            Object[] args = joinPoint.getArgs();
            Object body = args[0];
            // 反射获取参数值
            Object bodyField = ReflectUtil.getFieldValue(body, "name");
            if (!Objects.isNull(bodyField)){
                System.out.println(bodyField.toString());
            }
            Object bodyField2 = ReflectUtil.getFieldValue(body, "name2");
            if (!Objects.isNull(bodyField2)){
                System.out.println(bodyField2.toString());
            }
        }
    }

}
